//
//  MainViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "UIViewController+MMDrawerController.h"

#import "qjTableViewController.h"
#import "MainViewController.h"
#import "OALoginViewController.h"
#import "itemcell.h"
#import "OABaseNavViewController.h"
#import "ComingworkongController.h"
#import "emailViewController.h"
#import "iseditViewController.h"
#import "overworkingViewController.h"
#import "comingthingViewController.h"
#import "ideitworkViewController.h"
#import "workedViewController.h"
#import "OANewInViewController.h"
#import "OANewSendViewController.h"
#import "NotonewsViewController.h"
#import "webViewController.h"
#import "OAAddressViewController.h"
#import "OASMSViewController.h"
#import "MainViewCell.h"
#import "BaseModel.h"
#import "OASendMessageViewController.h"
#import "OAInBoxViewController.h"
#import "MYCycleView.h"

@interface HomeModel : BaseModel

@property(nonatomic,copy)NSString *  exchange;
@property(nonatomic,copy)NSString *  ksmail;
@property(nonatomic,copy)NSString *  mail;
@property(nonatomic,copy)NSString *  offiece;
@property(nonatomic,copy)NSString *  whetherExchange;
@property(nonatomic,copy)NSString *  whetherSms;
@property(nonatomic,copy)NSString * read;
@end
@implementation HomeModel


@end
@interface MainViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) UIButton *button1;
@property (nonatomic,strong) UIButton *button2;
@property(nonatomic,strong)NSMutableArray * contentArray;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic, strong) MYCycleView *cycleView;

//@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *followLayout;
//@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
//@property (nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong)HomeModel * homeModel;
@property(nonatomic,strong)NSMutableArray * originalData;
@property(nonatomic,strong)NSArray * array;
#define kWB_Login_NotificationName @"requestdata"
@end

@implementation MainViewController
static NSString * const reuseIdentifier = @"CellIdentifier";
-(NSMutableArray*)contentArray{
    if (_contentArray == nil) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11.0, *)) {
        self.additionalSafeAreaInsets= LL_ViewSafeAreInsets(self.view);
    } else {
    self.automaticallyAdjustsScrollViewInsets = NO;
            // Fallback on earlier versions
    }
//    self.navigationController.navigationBar.translucent = YES;
//    if (@available(iOS 11.0, *)) {
// self.additionalSafeAreaInsets= LL_ViewSafeAreInsets(self.view);
//    }else {
//self.automaticallyAdjustsScrollViewInsets = NO;
//}
//    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
//        self.automaticallyAdjustsScrollViewInsets = NO;
//}
// 更改标题的颜色

    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:

[UIColor whiteColor],NSForegroundColorAttributeName, nil];
 
[self.navigationController.navigationBar setTitleTextAttributes:attributes];
self.title = @"主页";
 self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:76/255.0 green:151/255.0 blue:231/255.0 alpha:1];
   [self _backbutton];
    //  [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"标题"] forBarMetrics:UIBarMetricsDefault];
     NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];


//定时器
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(news) userInfo:nil repeats:YES];
        // 开启当前线程
        [[NSRunLoop currentRunLoop] run];
    });
      //修改返回按钮的颜色和字体
  self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
          //修改返回按钮的颜色和字体
  self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
   UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;
 
    [self upApp];

}
- (void)initview{
if (!_collectionView) {
 self.view.backgroundColor = [UIColor colorWithHexString:@"f0eff5"];

     self.cycleView = [[MYCycleView alloc] initWithFrame:CGRectMake(0,kTopHeight, [UIScreen mainScreen].bounds.size.width, (KScreenHeight-kTopHeight)*1/3)];

//    当imageArray.cout为1时，不轮播，相当于imageView;
    self.cycleView.imageArray = @[@"banner_1_02.jpg",@"banner_2_02.jpg",@"banner_3_02.jpg"];
//    设置轮播时间，小于0时逆向，大于0时正向，等于0是不自动轮播
    self.cycleView.second = 10;
////    设置pageControl未选中indicator的颜色
    self.cycleView.pageIndicatorColor = [UIColor whiteColor];
//    设置pageControl当前indicator的颜色
    self.cycleView.currentIndicatorColor = [UIColor yellowColor];
    
    self.cycleView.bannerClick = ^(NSInteger index) {
        
        NSLog(@"点击了%zd",index);
        
    };
        [self.view addSubview:self.cycleView];



 UICollectionViewFlowLayout *followLayout = [[UICollectionViewFlowLayout alloc]init];
     followLayout.itemSize = CGSizeMake((KScreenWidth-3)/ 4,(KScreenWidth-3)/ 4 );

self.collectionView  = [[UICollectionView alloc]initWithFrame:CGRectMake(0,_cycleView.bottom, KScreenWidth, self.view.height-kTopHeight-_cycleView.height) collectionViewLayout:followLayout];
[self.view addSubview :_collectionView];
_collectionView.backgroundColor = [UIColor clearColor];
_collectionView.scrollEnabled = NO;
_collectionView.delegate = self;
_collectionView.dataSource = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"MainViewCell" bundle:nil] forCellWithReuseIdentifier:@"FansCellId"];
     followLayout.minimumLineSpacing =1;
        followLayout.minimumInteritemSpacing =1;



}

}
- (void)upApp{
 //获取app版本号
  NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    
    NSArray *array = @[@{@"veseion":appVersion},@{@"userId":userId}];

[HttpTools requestWithURL:KExchmain arrays:array method:@"updateDown" success:^(id JSON) {
if (![JSON isKindOfClass:[NSDictionary class]]) {
    [self.view makeToast:@"服务器出错!"];
}
//if ([JSON isEqualToString:@"-1044"]) {
//    [self.view makeToast:@"服务器出错!"];
//}
else{
         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
            NSString *url = dict[@"downlink"];
        NSString *index = dict[@"result"];
    
    
    if ([index isEqualToString:@"1"]) {
        
// 提示更新
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更新" message:@"APP已经更新，请点击确定进行更新" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel  handler:^(UIAlertAction * _Nonnull action) {
                
//    [[AuthHelper getInstance] logoutVpn];

    OALoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
//             loginVC.type = @"1";

    self.view.window.rootViewController = loginVC;
                
            }];

            UIAlertAction *action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                if (url.length != 0) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

                }
                
            }];
        
            [alert addAction:cancelAction];
            [alert addAction:action];
        
            [self presentViewController:alert animated:YES completion:nil];
        
        
       }
    
        }

    }failure:^(NSError *error) {
        
    }];

    

}

- (void)dealloc
{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kWB_Login_NotificationName object:nil];
    }
// 使用storyboard创建的控制调用的初始化方法
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        // 注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(news) name:kWB_Login_NotificationName object:nil];
       
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
  [self news];
}

- (void)news{
 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:KHomePqwoiunu success:^(id JSON) {
        [self initview];

         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
    _dic = dict;
        self.homeModel = [[HomeModel alloc] initWitDictionary:dict];
                    [self setupSubView];

            [self.collectionView reloadData];

    } failure:^(NSError *error) {
        
    }];


}
- (void)setupSubView{
NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];   
    
    self.contentArray = [self.originalData mutableCopy];
    [self.collectionView reloadData];


}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.contentArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MainViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FansCellId" forIndexPath:indexPath];
    NSDictionary * dict = self.contentArray[indexPath.item];
    cell.dict = dict;
//    itemcell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
//    NSDictionary * dict = self.contentArray[indexPath.item];
//    cell.dataList = _dataList[indexPath.row];

if ([dict[@"title"] isEqualToString:@"待办工作"]) {
        [cell.btnCount setTitle:self.homeModel.offiece forState:UIControlStateNormal];
        if ([self.homeModel.offiece integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }
//    else if ([dict[@"title"]isEqualToString:@"待办事项"]) {
//        [cell.btnCount setTitle:self.homeModel.read forState:UIControlStateNormal];
//        if ([self.homeModel.read integerValue] !=0) {
//            cell.btnCount.hidden = NO;
//        }else{
//            cell.btnCount.hidden = YES;
//        }
//        
//    }
    
    else if ([dict[@"title"] isEqualToString:@"收件箱"]) {
        [cell.btnCount setTitle:self.homeModel.mail forState:UIControlStateNormal];
        if ([self.homeModel.mail integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }else{
        cell.btnCount.hidden = YES;
    }
    [cell layoutIfNeeded];
    return cell;


}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
// NSLog(@"cell #%ld was selected", (long)indexPath.row);
 UIStoryboard * storyBoard  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
   if (indexPath.row==0) {
   ComingworkongController *comvc =(ComingworkongController *) [storyBoard instantiateViewControllerWithIdentifier:@"comvc"];
    [self.navigationController pushViewController:comvc animated:YES];
    }
    if (indexPath.row==1) {
  iseditViewController *isedvc =(iseditViewController *) [storyBoard instantiateViewControllerWithIdentifier:@"isedit"];
    [self.navigationController pushViewController:isedvc animated:YES];
    }
    if (indexPath.row==2) {
   overworkingViewController *overvc = (overworkingViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"over"];
    [self.navigationController pushViewController:overvc animated:YES];
    }
    if (indexPath.row==3) {
//   comingthingViewController *comthvc = (comingthingViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"comingthing"];
//       [self.navigationController pushViewController:comthvc animated:YES];
     NotonewsViewController *notonews = (NotonewsViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"notonews"];
     notonews.type = @"school";
     notonews.string = @"学校通知";
     notonews.url1 =@"http://mobileoa.zjxu.edu.cn:8082/IOSJXXYOA/jh/exchdata";
     notonews.method1 =@"setPublishNotice";
    [self.navigationController pushViewController:notonews animated:YES];
    }
    if (indexPath.row==4) {
    NotonewsViewController *notonews = (NotonewsViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"notonews"];
     notonews.string = @"部门通知";
     notonews.url1 =@"http://mobileoa.zjxu.edu.cn:8082/IOSJXXYOA/jh/exchdata";
     notonews.method1 =@"setDepPublishNotice";
    [self.navigationController pushViewController:notonews animated:YES];
    }
    if (indexPath.row==5) {
    OAInBoxViewController *invc = (OAInBoxViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"inbox"];
    [self.navigationController pushViewController:invc animated:YES];
//workedViewController *worked = (workedViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"worked"];
//    [self.navigationController pushViewController:worked animated:YES];
    }
    if (indexPath.row==6) {
    OASendMessageViewController *sendvc = (OASendMessageViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"send"];
    [self.navigationController pushViewController:sendvc animated:YES];
//     NotonewsViewController *notonews = (NotonewsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"notonews"];
//    [self.navigationController pushViewController:notonews animated:YES];
}
    if (indexPath.row==7) {
   workedViewController *worked = (workedViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"worked"];
    [self.navigationController pushViewController:worked animated:YES];    }
    if (indexPath.row==8) {
 qjTableViewController*oAnewView =  [[qjTableViewController alloc]init];
   //OANewInView
    [self.navigationController pushViewController:oAnewView animated:YES];
    }
    if (indexPath.row==9) {
   OANewSendViewController *oAnewSend = (OANewSendViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"OANewIn"];
    [self.navigationController pushViewController:oAnewSend animated:YES];
    }
    if (indexPath.row==10) {
   OAAddressViewController * addressVC = (OAAddressViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"AddressVCID"];
        [self.navigationController pushViewController:addressVC animated:YES];
    }
    if (indexPath.row==11) {
   OASMSViewController *smvc = (OASMSViewController *)[ storyBoard instantiateViewControllerWithIdentifier:@"SMSVCID"];
    [self.navigationController pushViewController:smvc animated:YES];
    }
    if (indexPath.row==12) {
  webViewController *webvc = [[webViewController alloc]init];
[self.navigationController pushViewController:webvc  animated:YES];
webvc.url = @"http://www.ccpitzj.gov.cn/index_r.html";    }
    if (indexPath.row==13) {
//   webViewController *webvc = [[webViewController alloc]init];
//[self.navigationController pushViewController:webvc  animated:YES];
//webvc.url = @"http://zw.ccpitzj.gov.cn/index_r.html";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://zw.ccpitzj.gov.cn/index_r.html"]];
}

   
   }




- (void)_backbutton{
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
rightButton.frame = CGRectMake(0, 0, 44, 44);
                [rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                    [rightButton setTitle:@"退出" forState:UIControlStateNormal];
                    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                 
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
     UIBarButtonItem * rightItem1  = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"3、首页-更多"] style:UIBarButtonItemStylePlain target:self action:@selector(createNewSMSAction)];

[self.navigationItem setLeftBarButtonItems:@[rightItem1]];

    
    
}
-(void)createNewSMSAction{
    
     [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];

    
}
- (void)rightButtonAction:(UIButton *)button {

 UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"是否退出登陆" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

if (buttonIndex == 1){
 UIStoryboard * storyBoard  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];

 OALoginViewController * loginVC =  [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
     [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
    self.view.window.rootViewController = loginVC;

}
}
@end
